<!--分散式房源房间配置表单-->
<template>
	<div class="house-form-romms">
		<a-typography-text strong>
			<blockquote>房型信息</blockquote>
		</a-typography-text>
		<a-space>
			<a-card v-if="loading.roomType" :loading="loading.roomType" class="room-type-card">
				<div />
			</a-card>
			<a-card v-else v-for="item in roomTypes" :key="item.id" size="small" hoverable class="room-type-card">
				<a-typography-text type="secondary">
					<small>房型模板</small>
				</a-typography-text>
				<a-space class="room-type-actions">
					<a-tooltip title="配置房型模板" placement="bottom">
						<setting-two-tone @click="editRoomType(item)" />
					</a-tooltip>
					<a-tooltip title="删除房型模板" placement="bottom" v-if="!item?.talentedHouseStatus">
						<close-circle-two-tone two-tone-color="red" @click="deleteRoomType(item)" />
					</a-tooltip>
				</a-space>
				<small>
					{{ item.name }}
				</small>
			</a-card>
			<a-button type="primary" ghost class="room-type-add-btn" @click="editRoomType()">
				<plus-outlined />
			</a-button>
		</a-space>
		<a-typography-text strong>
			<blockquote>房间信息</blockquote>
		</a-typography-text>
		<a-card v-if="buildings && buildings.length" size="small" type="inner" class="rooms-card">
			<template #title>
				<a-select v-model:value="buildingId" v-bind="buildingOptions" />
			</template>
			<template #extra>
				<a-skeleton-input v-if="loading.house" active size="small" style="width: 500px" />
				<template v-else>
					共&nbsp;&nbsp;
					<a-tag color="blue">{{ currentBuilding.roomQuantity }}</a-tag>
					间
					<a-divider type="vertical" />
					启用&nbsp;&nbsp;
					<a-tag color="green">{{ currentBuilding.normalQuantity }}</a-tag>
					间
					<a-divider type="vertical" />
					禁用&nbsp;&nbsp;
					<a-tag color="red">{{ currentBuilding.disabledQuantity }}</a-tag>
					间
					<a-divider type="vertical" />
					未分配&nbsp;&nbsp;
					<a-tag color="orange">{{ currentBuilding.unallocatedQuantity }}</a-tag>
					间
				</template>
			</template>
			<draggable v-model="currentBuilding.floorList" handle=".floor-sort-handle" @end="updateFloors" animation="300" item-key="floor">
				<template #item="{element}">
					<a-collapse v-model:active-key="activeKeys" expand-icon-position="right" destroy-inactive-panel :bordered="false">
						<a-collapse-panel :key="element.floor">
							<template #header>
								<a-skeleton-button v-if="loading.house" size="small" active block />
								<template v-else>
									<a class="floor-sort-handle">
										<unordered-list-outlined />
									</a>
									<a-typography-text
										strong
										:content="element.floorNo"
										:editable="{
											maxlength: 10,
											onEnd: () => updateFloorName(element),
											onChange: str => (element.newFloorNo = str)
										}"
										:ellipsis="{
											suffix: ` 层（共${(element.roomList || []).length - 1}间）`
										}"
										@click.stop.prevent>
										{{ element.floorNo }}
										<template #editableTooltip>编辑楼层号</template>
									</a-typography-text>
								</template>
							</template>
							<template #extra>
								<template v-if="(selectionMap[element.floor] || []).length">
									<a-button type="link" size="small" @click.stop="batchEnableOrDisable(element.floor, 1)">
										批量启用
									</a-button>
									<a-button
										type="link"
										danger
										size="small"
										v-if="!(selectionMap[element.floor] || []).filter(e => talentedList.includes(e.id)).length"
										@click.stop="batchEnableOrDisable(element.floor, 2)">
										批量禁用
									</a-button>
									<a-button
										type="link"
										danger
										size="small"
										v-if="!(selectionMap[element.floor] || []).filter(e => talentedList.includes(e.id)).length"
										@click.stop="batchRemove(element.floor)">
										批量删除
									</a-button>
								</template>
								<a-button v-if="!loading.house && element.roomList" @click.stop type="link" size="small">
									<a-checkbox
										:disabled="0 === (element.roomList || []).filter(j => hasConfig(j)).length"
										:checked="
											0 !== (element.roomList || []).filter(j => hasConfig(j)).length &&
											(selectionMap[element.floor] || []).length ===
												(element.roomList || []).filter(j => hasConfig(j)).length
										"
										@change="e => selectAllRooms(e, element, 1)">
										已配置
									</a-checkbox>
									<!-- roomList中有一个是空对象 需要剔除 所以长度-1 -->
									<a-checkbox
										:disabled="0 === (element.roomList || []).filter(j => !hasConfig(j)).length - 1"
										:checked="
											0 !== (element.roomList || []).filter(j => !hasConfig(j)).length - 1 &&
											(selectionMap[element.floor] || []).length ===
												(element.roomList || []).filter(j => !hasConfig(j)).length - 1
										"
										@change="e => selectAllRooms(e, element, 2)">
										未配置
									</a-checkbox>
								</a-button>
							</template>
							<a-checkbox-group v-model:value="selectionMap[element.floor]" style="width: 100%">
								<a-list
									:id="`floor_${element.floor}`"
									:data-source="element.roomList"
									:grid="{gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 5, xxxl: 7}">
									<template #renderItem="{item}">
										<a-list-item>
											<a-checkbox
												v-if="item.id !== undefined"
												:value="item"
												:disabled="loading.house || disabledOperate(item)"
												class="room-check-card-wrapper">
												<a-card
													size="small"
													:loading="loading.house"
													:class="[
														'room-check-card',
														item.status === 60 ? 'disabled' : '',
														disabledOperate(item) ? 'disabled-operate' : ''
													]">
													<a-space class="room-check-card-actions">
														<a-tooltip
															title="删除房间"
															placement="bottom"
															v-if="!talentedList.includes(item.id)">
															<close-circle-two-tone
																two-tone-color="red"
																@click.stop.prevent="deleteRoom(item)" />
														</a-tooltip>
													</a-space>
													<a-typography-text
														strong
														:content="item.roomName"
														:disabled="item.status === 60"
														:editable="{
															maxlength: 10,
															onEnd() {
																item.roomName = item.newRoomName || item.roomName
																saveRoomName(item)
															},
															onChange: str => (item.newRoomName = str)
														}">
														<template #editableTooltip>编辑房间号</template>
													</a-typography-text>
													<a-tag :color="HOUSE_COLOR_MAP[item.status]" class="house-status-tag">
														{{ HOUSE_STATUS_MAP[item.status].label }}
													</a-tag>
													<template v-if="item.roomTypeId">
														<a-typography-paragraph type="secondary" :disabled="item.status === 60">
															<small>{{ item.roomTypeName }}</small>
														</a-typography-paragraph>
														<a-typography-paragraph type="secondary" :disabled="item.status === 60">
															<a-space>
																<small>{{ item.rentalPrice }}元/月</small>
																<small>
																	{{ orientationMap[item.orientation] || '未知' }}-{{
																		item.houseArea || 0
																	}}㎡
																</small>
															</a-space>
														</a-typography-paragraph>
													</template>
												</a-card>
											</a-checkbox>
											<a-button v-else type="primary" ghost class="room-add-btn" @click="addRoom(element)">
												<plus-outlined />
											</a-button>
										</a-list-item>
									</template>
								</a-list>
							</a-checkbox-group>
						</a-collapse-panel>
					</a-collapse>
				</template>
			</draggable>
		</a-card>
		<a-empty v-else class="house-empty" style="flex: 1" />
		<a-form ref="form" :model="config" :rules="roomConfigRules" layout="vertical" class="batch-config-form">
			<a-typography-paragraph strong>
				<template v-if="selections.length">
					对 【
					<span class="room-selections">{{ selections.map(o => o.roomName).join() }}</span>
					】 房间进行统一配置
				</template>
				<template v-else>请选择房间</template>
			</a-typography-paragraph>
			<a-row :gutter="16">
				<a-col :span="community.houseBizMode === 1 ? 4 : 5">
					<a-form-item name="roomTypeId">
						<template #label>
							<a-checkbox
								v-if="disabledCheckRoom"
								v-model:checked="configCheck.checkRoomTypeId.check"
								style="margin-right: 5px"></a-checkbox>
							<span>房型</span>
						</template>
						<a-select
							v-model:value="config.roomTypeId"
							v-bind="roomTypeOptions"
							:disabled="
								(disabledCheckRoom && !configCheck.checkRoomTypeId.check) ||
								(selections || []).filter(e => talentedList.includes(e.id)).length
							" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item name="rentalPrice">
						<template #label>
							<a-checkbox
								v-if="disabledCheckRoom"
								v-model:checked="configCheck.checkRentalPrice.check"
								@change="configCheck.checkBasePrice.check = true"
								style="margin-right: 5px"></a-checkbox>
							<span>出租价（元）</span>
						</template>
						<a-input-number
							:disabled="disabledCheckRoom && !configCheck.checkRentalPrice.check"
							v-model:value="config.rentalPrice"
							:precision="2"
							:min="config.basePrice || 0"
							@change="basePriceChange"
							placeholder="请输入" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item name="basePrice">
						<template #label>
							<a-checkbox
								v-if="disabledCheckRoom"
								v-model:checked="configCheck.checkBasePrice.check"
								style="margin-right: 5px"></a-checkbox>
							<span>底价（元）</span>
						</template>
						<a-input-number
							:disabled="disabledCheckRoom && !configCheck.checkBasePrice.check"
							v-model:value="config.basePrice"
							:precision="2"
							:min="0"
							:max="config.rentalPrice"
							placeholder="请输入" />
					</a-form-item>
				</a-col>
				<a-col :span="3" v-if="community.houseBizMode === 1">
					<a-form-item name="costPrice">
						<template #label>
							<a-checkbox
								v-if="disabledCheckRoom"
								v-model:checked="configCheck.checkCostPrice.check"
								style="margin-right: 5px"></a-checkbox>
							<span>收房价（元）</span>
						</template>
						<a-input-number
							:disabled="disabledCheckRoom && !configCheck.checkBasePrice.check"
							v-model:value="config.costPrice"
							:precision="2"
							:min="0"
							:max="999999999.99"
							placeholder="请输入" />
					</a-form-item>
				</a-col>
				<a-col :span="community.houseBizMode === 1 ? 2 : 3">
					<a-form-item name="houseArea">
						<template #label>
							<a-checkbox
								v-if="disabledCheckRoom"
								v-model:checked="configCheck.checkHouseArea.check"
								style="margin-right: 5px"></a-checkbox>
							<span>面积</span>
						</template>
						<a-input-number
							:disabled="disabledCheckRoom && !configCheck.checkHouseArea.check"
							v-model:value="config.houseArea"
							:precision="2"
							:min="0"
							placeholder="请输入" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item name="orientation">
						<template #label>
							<a-checkbox
								v-if="disabledCheckRoom"
								v-model:checked="configCheck.checkOrientation.check"
								style="margin-right: 5px"></a-checkbox>
							<span>朝向</span>
						</template>
						<a-select
							:disabled="disabledCheckRoom && !configCheck.checkOrientation.check"
							v-model:value="config.orientation"
							:options="orientationList"
							allow-clear
							show-search
							placeholder="请选择朝向" />
					</a-form-item>
				</a-col>
				<a-col :span="community.houseBizMode === 1 ? 2 : 3">
					<a-form-item name="userlimit">
						<template #label>
							<a-checkbox
								v-if="disabledCheckRoom"
								v-model:checked="configCheck.checkUserlimit.check"
								style="margin-right: 5px"></a-checkbox>
							<span>可住人数</span>
						</template>
						<a-input-number
							:disabled="disabledCheckRoom && !configCheck.checkUserlimit.check"
							v-model:value="config.userlimit"
							:min="0"
							:precision="0"
							placeholder="请输入" />
					</a-form-item>
				</a-col>
				<a-col :span="3">
					<a-form-item name="avaliableDate">
						<template #label>
							<a-checkbox
								v-if="disabledCheckRoom"
								v-model:checked="configCheck.checkAvaliableDate.check"
								style="margin-right: 5px"></a-checkbox>
							<span>可租日期</span>
						</template>
						<a-date-picker
							:disabled="disabledCheckRoom && !configCheck.checkAvaliableDate.check"
							v-model:value="config.avaliableDate"
							:value-format="DATE_FORMAT.DATE"
							placeholder="请选择" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
	</div>
	<teleport to=".house-edit-dialog .ant-modal-footer">
		<a-button type="primary" :loading="loading.save" @click="saveBatch()">保存</a-button>
		<a-button type="primary" ghost :loading="loading.save" @click="saveBatch(true)">下一步，完善推广信息</a-button>
	</teleport>
	<room-type-edit-dialog v-model:visible="visibles.roomTypeEdit" :value="roomType" @close="getRoomTypes" />
</template>

<script lang="ts" setup>
	import {computed, createVNode, reactive, ref, nextTick} from 'vue'
	import Draggable from 'vuedraggable-es'
	import {Building, Community, defaultRoomType, Floor, Room, RoomType} from '@/interface/community'
	import {
		CloseCircleTwoTone,
		PlusOutlined,
		QuestionCircleOutlined,
		SettingTwoTone,
		EditOutlined,
		UnorderedListOutlined
	} from '@ant-design/icons-vue'
	import houseApi from '@/api/house-api'
	import {COLOR_MAP, DEFAULT_FIELD_NAME} from 'yuxin-base/src/constant'
	import {defaultRoom, HOUSE_COLOR_MAP, HOUSE_STATUS_MAP, orientationList, orientationMap} from '@/interface/house'
	import RoomTypeEditDialog from '@/components/house/edit/centralized/room-type-edit-dialog.vue'
	import {message, Modal} from 'ant-design-vue'
	import DATE_FORMAT from 'yuxin-base/src/utils/date'
	import {roomRules} from '@/rules/community'
	import {FormExpose} from 'ant-design-vue/lib/form/Form'
	import {useStore} from '@/store/index'
	import XEUtils from 'xe-utils'
	import {watchEffect} from 'vue'
	import house from '@/router/house'

	const hasPermissions = useStore().hasPermissions

	const props = defineProps<{
		value: Community
	}>()
	const enabled = ref(true)
	const dragging = ref(false)
	const emits = defineEmits(['next'])

	const loading = reactive({
		save: false,
		house: true,
		roomType: true
	})

	const visibles = reactive({
		roomTypeEdit: false
	})

	const form = ref<FormExpose>()
	// 房间配置
	const config = ref<Room>({
		specialPrice: 0
	})
	const roomConfigRules = reactive(XEUtils.clone(roomRules(config.value)))
	// 选择房间配置加上选择框(已经配置的房间才显示check选项 但是已配置的房间不能和未配置的房间一起选中)
	const configCheck = ref({
		// 房型
		checkRoomTypeId: {
			check: false,
			key: 'roomTypeId'
		},
		// 出租价
		checkRentalPrice: {
			check: false,
			key: 'rentalPrice'
		},
		// 底价
		checkBasePrice: {
			check: false,
			key: 'basePrice'
		},
		//收房价
		checkCostPrice: {
			check: false,
			key: 'costPrice'
		},
		// 面积
		checkHouseArea: {
			check: false,
			key: 'houseArea'
		},
		// 朝向
		checkOrientation: {
			check: false,
			key: 'orientation'
		},
		// 可住人数
		checkUserlimit: {
			check: false,
			key: 'userlimit'
		},
		// 可租日期
		checkAvaliableDate: {
			check: false,
			key: 'avaliableDate'
		}
	})
	const resetCheck = (flag = false) => {
		Object.values(configCheck.value).forEach(i => (i.check = flag))
	}
	const basePriceChange = () => {
		config.value.basePrice = config.value.rentalPrice
		configCheck.value.checkBasePrice.check = true
	}
	// 当前编辑的房型
	const roomType = ref<Room>()
	const activeKeys = ref<string[]>(['placeholder'])

	// 是否配置房源信息
	const hasConfig = (roomInfo: any) => {
		// 是否配置房型 && 出租价 && 面积 && 朝向
		if (community.houseBizMode == 1) {
			//代理+收房价
			return Boolean(
				roomInfo.roomTypeId &&
					roomInfo.rentalPrice &&
					roomInfo.basePrice &&
					roomInfo.costPrice &&
					roomInfo.houseArea &&
					roomInfo.orientation
			)
		}
		return Boolean(roomInfo.roomTypeId && roomInfo.rentalPrice && roomInfo.basePrice && roomInfo.houseArea && roomInfo.orientation)
	}
	// 存放选中的房间
	const selectionMap = ref<any>({})
	const selections = computed(() => Object.values(selectionMap.value).flat())
	// 判断有配置的房间数量大于0(如果大于0 未配置的房间要禁用 配置房间的时候显示checkbox 非必填 , 未配置的房间隐藏 必填)
	const disabledCheckRoom = computed(() => {
		return selections.value.filter(i => hasConfig(i)).length > 0
	})
	// 是否必填
	watchEffect(() => {
		// disabledCheckRoom为true表示选择的是已经配置过房间类型的房间 这时候遍历configCheck再去取值 除了可住人数其他勾选的全部必填
		if (disabledCheckRoom.value) {
			const checkKeys = Object.values(configCheck.value)
			Object.keys(roomConfigRules).forEach(i => {
				if ('userlimit' === i) {
					roomConfigRules['userlimit'][0].required = false
					return
				}
				if (checkKeys.filter(j => j.key === i).length > 0) {
					roomConfigRules[i][0].required = checkKeys.filter(j => j.key === i)[0].check
				}
			})
			nextTick(() => {
				// 清除校验 不清除input框会无法随checkbox按钮的开关控制禁用
				form?.value?.clearValidate()
			})
		} else {
			Object.values(roomConfigRules).forEach(i => (i[0].required = true))
		}
	})
	const disabledOperate = computed(() => {
		return roomItem => {
			if (!selections.value.length) return false
			const flag = hasConfig(selections.value[0])
			return !!(hasConfig(roomItem) !== flag)
		}
	})
	// 项目信息
	const community = reactive<Community>(props.value)
	// 房型列表
	const roomTypes = ref<RoomType[]>([])
	const getRoomTypes = () => {
		loading.roomType = true
		houseApi
			.getRoomTypeList(community.id as string)
			.then(({data}) => {
				roomTypes.value = data

				if (data.length) {
					getRoomsByRoomTypeId()
				}
			})
			.finally(() => (loading.roomType = false))
	}
	//查询房型是否有认定中或者认定通过的房间
	const roomTypeTalentedIds = ref<any>([])
	const talentedList = ref<any>([])
	const getRoomsByRoomTypeId = () => {
		roomTypeTalentedIds.value = []
		talentedList.value = []
		roomTypes.value.forEach(e => {
			houseApi.getRoomsByRoomTypeId(e.id).then(res => {
				e.talentedHouseStatus = res.data && res.data.length ? true : false
				if (e.talentedHouseStatus) {
					roomTypeTalentedIds.value.push(e.id)
					res.data.forEach(o => talentedList.value.push(o.id))
				}
			})
		})
	}
	const defaultFloorList = [{floor: 'placeholder', roomList: Array.from(new Array(15)).map(defaultRoom)}]

	// 楼栋列表
	const buildings = ref<Building[]>()
	const buildingId = ref()
	const currentBuilding = ref<Building>({floorList: defaultFloorList})
	const buildingOptions = reactive({
		options: buildings,
		showSearch: true,
		optionFilterProp: 'name',
		fieldNames: DEFAULT_FIELD_NAME,
		onChange() {
			getBuildingRooms()
		},
		style: {
			width: '200px'
		}
	})
	// 根据楼栋获取房间列表
	const getBuildingRooms = (created?: boolean) => {
		if (!created) {
			loading.house = true
			currentBuilding.value = {floorList: defaultFloorList}
			activeKeys.value = ['placeholder']
		}

		houseApi
			.getBuildingRoomList(buildingId.value)
			.then(({data}) => {
				const {floorList = [{}]} = data

				for (let {roomList} of floorList) {
					// 添加一条数据显示添加房间按钮
					roomList.push({})
				}

				currentBuilding.value = data

				selectionMap.value = {}
				if (!created) {
					activeKeys.value = [floorList[0].floor]
				}
			})
			.catch(() => {
				activeKeys.value = []
				currentBuilding.value = {}
			})
			.finally(() => (loading.house = false))
	}

	if (community && community.id) {
		getRoomTypes()

		houseApi.getBuildingList(community.id).then(({data}) => {
			buildings.value = data
			if (data && data.length) {
				buildingId.value = data[0].id
				getBuildingRooms()
			}
		})
	}

	const roomTypeOptions = reactive({
		options: roomTypes,
		showSearch: true,
		optionFilterProp: 'name',
		placeholder: '请选择房型',
		fieldNames: DEFAULT_FIELD_NAME,
		onSelect(value: string, option: RoomType) {
			config.value.houseArea = option.area
			config.value.basePrice = option.basePrice
			config.value.costPrice = option?.costPrice || null
			config.value.rentalPrice = option.rentalPrice
			config.value.orientation = option.orientation
			config.value.avaliableDate = option.avaliableDate
			config.value.userlimit = option.userLimit
		}
	})

	// 编辑、新增房型
	const editRoomType = (item?: RoomType) => {
		visibles.roomTypeEdit = true
		roomType.value = item || {...defaultRoomType(), communityId: community.id, houseBizMode: community.houseBizMode}
		roomType.value.houseBizMode = community.houseBizMode
	}

	// 删除房型
	const deleteRoomType = (item: RoomType) => {
		Modal.confirm({
			title: '系统提示',
			content: '房型删除后无法恢复，确定删除？',
			mask: true,
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			async onOk() {
				await houseApi.removeRoomType(item.id as string)
				getRoomTypes()
				message.success('房型删除成功')
			}
		})
	}

	/**
	 * 选中操作
	 * @param type 1 已配置 2 未配置
	 */
	const selectAllRooms = (e: any, floor: Floor, type: number) => {
		const {target} = e
		const getRightFloor =
			1 === type ? floor.roomList?.filter(o => o.id && hasConfig(o)) : floor.roomList?.filter(o => o.id && !hasConfig(o))
		selectionMap.value[floor.floor as string] = target.checked ? getRightFloor : []

		// 需要判断其他的房间也要是同样的配置状态 防止已配置和未配置互斥
		Object.keys(selectionMap.value).forEach(i => {
			if (i === (floor.floor as string)) return
			const legalArr =
				1 === type
					? (selectionMap.value[i as string] || []).filter(o => o.id && hasConfig(o))
					: (selectionMap.value[i as string] || []).filter(o => o.id && !hasConfig(o))
			selectionMap.value[i as string] = legalArr
		})
		console.log(floor.roomList, 'floor.roomList')
		console.log(selectionMap.value, 'legalArr')
	}

	/**
	 * 删除房间
	 * @param item
	 */
	const deleteRoom = (item: Room) => {
		if (item.status !== 11) {
			return message.warning('房间非空置状态不可操作删除')
		}
		Modal.confirm({
			width: 470,
			title: '系统提示',
			content: () =>
				createVNode('div', {}, [
					createVNode('div', {
						innerHTML: '请确定相关房间的在租合约、固定资产、智能设备已清空'
					}),
					createVNode('div', {
						innerHTML: '房间删除后无法恢复, 确定删除',
						style: {
							color: COLOR_MAP.danger
						}
					})
				]),
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			okText: '删除',
			okType: 'danger',
			async onOk() {
				await houseApi.removeRoom(item.id as string)
				getBuildingRooms(true)
				message.success('房间删除成功')
			}
		})
	}

	/**
	 * 保存房间号
	 * @param item
	 */
	const saveRoomName = (item: Room) => {
		houseApi.saveRoomName(item).then(() => {
			message.success('房间号更新成功')
		})
	}

	/**
	 * 批量启用或禁用房间
	 * @param rooms 房间列表
	 * @param opType 1启用、2禁用
	 */
	const batchEnableOrDisable = (floor: any, opType: number) => {
		const houseRoomIdList = selectionMap.value[floor].map((o: Room) => o.id)

		if (houseRoomIdList.length === 0) {
			return message.warning('请选择需要操作的房间')
		}

		Modal.confirm({
			title: '系统提示',
			content: `是否批量${opType === 1 ? '启用' : '禁用'}已选择房间`,
			mask: true,
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			async onOk() {
				await houseApi.batchEnableOrDisableRooms({houseRoomIdList, opType})
				getBuildingRooms(true)
				message.success('操作成功')
			}
		})
	}

	/**
	 * 批量删除房间
	 * @param rooms 房间列表
	 */
	const batchRemove = (floor: any) => {
		const ids = selectionMap.value[floor].map((o: Room) => o.id)
		const del = selectionMap.value[floor].every((item, index) => {
			return item.status === 11
		})
		if (ids.length === 0) {
			return message.warning('请选择需要删除的房间')
		}
		if (!del) {
			return message.warning('房间非空置状态不可操作删除')
		}
		Modal.confirm({
			title: '系统提示',
			content: '是否删除已选择房间',
			mask: true,
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			async onOk() {
				await houseApi.batchRemoveRooms(ids)
				getBuildingRooms(true)
				message.success('删除成功')
			}
		})
	}

	/**
	 * 添加房间
	 * @param room
	 */
	const addRoom = (floor: Floor) => {
		houseApi
			.addRoom({
				floor: floor.floor,
				floorNo: floor.floorNo,
				buildingId: buildingId.value
			})
			.then(() => {
				message.success('添加成功')
				getBuildingRooms(true)
			})
	}

	const saveBatch = (next?: boolean) => {
		if (selections.value.length === 0) {
			if (next) {
				return emits('next')
			}
			return message.warning('请先选择需要配置的房间')
		}

		const getConfigParams = XEUtils.clone(config.value)

		// 已经配置过的房间要把没勾选的字段值设为NULL
		if (disabledCheckRoom.value) {
			// 获取未勾选的字段值
			const getCheckField = Object.values(configCheck.value)
				.filter(i => !i.check)
				.map(i => i.key)
			Object.keys(getConfigParams).forEach(i => {
				if (getCheckField.includes(i)) {
					getConfigParams[i] = null
				}
			})
		}

		form.value?.validate().then(() => {
			loading.save = true
			houseApi
				.saveBatchRoomConfig({
					...getConfigParams,
					houseRoomIdList: selections.value.map((o: any) => o.id)
				})
				.then(() => {
					message.success('保存成功')
					resetCheck()
					next ? emits('next') : getBuildingRooms(true)
				})
				.finally(() => (loading.save = false))
		})
	}

	// 编辑更新编辑楼层名称
	const updateFloorName = (floor: Floor) => {
		if (!XEUtils.trim(floor.newFloorNo)) {
			return message.error('请输入楼层号')
		}

		if (floor && floor.newFloorNo) {
			// 判断新楼层号是否重复
			const exist = currentBuilding.value.floorList?.find(e => e.floorNo === floor.newFloorNo)
			if (exist && exist !== floor) {
				return message.error(`楼层号【${floor.newFloorNo}】重复，请重新输入`)
			} else {
				floor.floorNo = floor.newFloorNo
			}
		}

		houseApi
			.updateFloorNumber({
				floor: floor.floor,
				floorNo: floor.floorNo,
				buildingId: currentBuilding.value.id
			})
			.then(() => message.success('后台数据正在同步更新，请稍候'))
	}

	const updateFloors = () => {
		const data = {
			buildingId: currentBuilding.value.id,
			floors: currentBuilding.value.floorList?.map((e, i) => {
				return {
					floor: i + 1,
					floorNo: e.floorNo
				}
			})
		}

		houseApi.updatePropertyFloor(data).then(() => message.success('后台数据正在同步更新，请稍候'))
	}
</script>

<style lang="less" scoped>
	.room-selections {
		color: @primary-color;
	}

	.house-form-romms {
		min-height: 100%;
		display: flex;
		flex-direction: column;

		.room-type-card {
			width: 200px;
			height: 60px;

			:deep(.ant-card-body) {
				height: 100%;
				padding: 4px 8px;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.room-type-actions {
					right: 8px;
					display: none;
					position: absolute;
				}

				&:hover .room-type-actions {
					display: inline-flex;
				}
			}
		}

		.room-type-add-btn {
			height: 60px;
			width: 60px;
			font-size: 24px;
			border-style: dashed;
		}

		.rooms-card {
			flex: 1;
			display: flex;
			min-height: 450px;
			flex-direction: column;

			:deep(.ant-card-body) {
				flex: 1;
				flex-basis: 0;
				overflow: auto;

				.ant-collapse-item:last-child {
					border: 0;
				}

				.ant-collapse {
					border-bottom: 1px solid #d9d9d9;

					.floor-sort-handle {
						cursor: move;
						margin-right: 6px;
					}

					.ant-typography-edit-content {
						top: 4px;
						left: 0;
						margin-bottom: 0;

						.ant-input {
							min-height: 24px;
							line-height: 24px;
							padding: 0 0 0 8px;
						}
					}
				}
			}
		}

		.room-check-card-wrapper {
			width: 100%;

			:deep(.ant-checkbox) {
				top: 79px;
				right: 8px;
				z-index: 1;
				display: none;
				position: absolute;

				& + span {
					padding: 0;
					width: 100%;
				}
			}

			&.ant-checkbox-wrapper-checked {
				:deep(.ant-checkbox) {
					display: initial;
				}

				.room-check-card {
					border-color: @primary-color;
				}
			}

			.room-check-card {
				&.disabled {
					background: #f6f7f8;
				}
				&.disabled-operate {
					background: #f6f7f8;
					filter: grayscale(1);
					pointer-events: none;
				}

				:deep(.ant-card-body) {
					height: 90px;
					overflow: hidden;

					.house-status-tag {
						top: 12px;
						right: 12px;
						margin: 0;
						position: absolute;
						border-radius: 16px;
						font-size: @font-size-sm;
						transform: scale(90%);
					}

					.ant-typography {
						left: 0;
						margin: 0;
						z-index: 1;
						cursor: pointer;
						position: relative;

						.ant-typography-edit-content-confirm {
							bottom: 4px;
						}

						.ant-input {
							height: 22px !important;
							min-height: 22px !important;
							line-height: 20px !important;
							padding: 0 5px !important;
						}
					}

					.ant-typography-edit {
						display: none !important;
					}

					&:hover {
						.ant-typography-edit {
							display: inline-block !important;
						}
					}
				}

				.room-check-card-actions {
					top: -12px;
					right: -7px;
					display: none;
					position: absolute;

					.room-delete {
						color: @error-color;
					}
				}

				&:hover .room-check-card-actions {
					display: inline-flex;
				}
			}
		}

		.room-add-btn {
			width: 90px;
			height: 90px;
			font-size: 24px;
			margin-top: 4px;
			border-style: dashed;
		}

		.batch-config-form {
			margin-top: 16px;
			position: sticky;
			bottom: 0;
			z-index: 1;
			background: #fff;

			.ant-picker,
			.ant-input-number {
				width: 100%;
			}

			.ant-typography {
				margin: 0;
			}
		}
	}
</style>
